#include "gamehall.h"
#include "ui_gamehall.h"
#include <QCloseEvent>
gameHall::gameHall(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::gameHall)
{
    ui->setupUi(this);

    manager = new QNetworkAccessManager(this);
}

gameHall::~gameHall()
{
    delete ui;
}

void gameHall::get_info(QString ssid)
{
    //1.获取到输入框中的url
    QString name_http = "/info";
    QUrl url(URL + name_http);
    //2.构造一个HTTP请求对象
    QNetworkRequest request(url);
    //3.发送请求
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    qDebug() << "gamehall_ssid:" << ssid;
    request.setRawHeader("Cookie", ssid.toUtf8());
    response = manager->get(request);
    //response = manager->post(request, "body");
    //4.通过信号槽，来处理函数
    connect(response, &QNetworkReply::finished, this, &gameHall::handle_info);
}

void gameHall::ws_hall(QString ssid)
{
    _ssid = ssid;
    //构造：QWebSocket(const QString &origin = QString(), QWebSocketProtocol::Version version = QWebSocketProtocol::VersionLatest, QObject *parent = nullptr)
    //使用给定的源，要使用的协议版本和parent创建一个新的QWebSocket 。
    ws = new QWebSocket;//new一个客户端对象
    ws->setParent(this);
    QString name_ws = "/hall";
    QNetworkRequest ws_request(QUrl(WS_URL + name_ws));
    ws_request.setRawHeader("Cookie", ssid.toUtf8());
    ws->open(ws_request);
    //2.判断是否连接
    connect(ws, &QWebSocket::connected, this, &gameHall::connectHandle);//连接成功
    connect(ws, &QWebSocket::disconnected, this, &gameHall::disConnectHandle);//断开连接
    //connect(ws, &QWebSocket::error, this, &gameHall::errorHandle);//断开连接
    //4.接收数据
    connect(ws, &QWebSocket::textMessageReceived, this, &gameHall::recvMessageHandle);//发送消息

}

void gameHall::closeEvent(QCloseEvent *event)
{
    (void)event;
    ws->close();//关闭大厅连接
    //QMessageBox::information(this, "客户端消息", "关闭大厅连接", QMessageBox::Ok);
    qDebug() << "退出大厅页面";
}

void gameHall::handle_info()
{
    if(response->error() == QNetworkReply::NoError)
    {
        resp = response->readAll();
        qDebug() << "获取用户信息成功";
        //响应正确收取到了
        //QMessageBox::information(this, "服务端响应", resp, QMessageBox::Ok);
        //将获得的结果·进行反序列化
        QJsonParseError jsonError;
        QJsonDocument jsonDocument = QJsonDocument::fromJson(resp.toUtf8(), &jsonError);
        if(jsonError.error == QJsonParseError::NoError)
        {
            QJsonObject jsonObject = jsonDocument.object();
            ui->label_username->setText("姓名 : " + jsonObject["username"].toString().toUtf8());
            ui->label_score->setText("分数 : " + QString::number(jsonObject["score"].toInt()));
            ui->label_total->setText("总场数 : " + QString::number(jsonObject["total_count"].toInt()));
            ui->label_win->setText("胜场数 : " + QString::number(jsonObject["win_count"].toInt()));
        }
    }
    else
    {
        resp = response->readAll();
        qDebug() << "handle_info:" << resp;
        qDebug() << "获取用户信息失败";
        //响应出错了
        //QMessageBox::critical(this, "服务端响应", resp, QMessageBox::Ok);
        qDebug() << "返回登陆";
        Login* login = new Login;
        login->show();
        this->close();
    }
    //对response进行释放
    response->deleteLater();
}

void gameHall::on_pushButton_start_clicked()
{
    if(ui->pushButton_start->text() == "开始匹配")
    {
        QJsonObject req;//创建一个json对象
        req.insert("optype", "match_start");
        ws->sendTextMessage(QJsonDocument(req).toJson());
    }
    else
    {
        //ui->pushButton_start->setText("开始匹配");
        QJsonObject req;//创建一个json对象
        req.insert("optype", "match_stop");
        ws->sendTextMessage(QJsonDocument(req).toJson());
    }
}

void gameHall::connectHandle()
{
    qDebug() << "websocket_hall连接成功";
}

void gameHall::disConnectHandle()
{
    qDebug() << "websocket_hall断开连接";
}

//void gameHall::errorHandle(QAbstractSocket::SocketError error)
//{
//    qDebug() << "websocket_hall连接失败，原因为：" << error;
//}

void gameHall::recvMessageHandle(const QString &msg)
{
    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(msg.toUtf8(), &jsonError);
    if(jsonError.error == QJsonParseError::NoError)
    {
        QJsonObject jsonObject = jsonDocument.object();
        if(jsonObject["result"] == true)
        {
            //QMessageBox::information(this, "服务端响应", msg, QMessageBox::Ok);
            if(jsonObject["optype"].toString() == "match_start")
            {
                //QMessageBox::information(this, "客户端", "进入匹配队列", QMessageBox::Ok);
                ui->pushButton_start->setText("匹配中...点击按钮停止匹配");
            }
            else if(jsonObject["optype"].toString() == "match_success")
            {
                //QMessageBox::information(this, "客户端", _ssid + "对战匹配成功，进入房间！", QMessageBox::Ok);
                ws->close();//关闭连接
                gameRoom* gameroom = new gameRoom;
                gameroom->ws_room(_ssid);//在房间建立长连接
                this->close();
                gameroom->show();

            }
            else if(jsonObject["optype"].toString() == "match_stop")
            {
                //QMessageBox::information(this, "客户端", "退出匹配队列", QMessageBox::Ok);
                ui->pushButton_start->setText("开始匹配");
            }
        }
        else
        {
            //QMessageBox::critical(this, "服务端响应", msg, QMessageBox::Ok);
            ws->close();//关闭连接
            //建立连接失败，返回登录
            Login* login = new Login;
            this->close();
            login->show();

        }
    }
    else
    {
        ws->close();//关闭连接
        //获取请求失败，返回登录
        Login* login = new Login;
        this->close();
        login->show();

    }
}
